import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class CombineBlocks {
	static String BLOCK_PATH = "../predictions/AUS/val/310";
	static String TIME = getCurrentTimeStamp();
	static String OUT;
	static String NAME;
	static int NOS;
	static byte[] RES;

	public static void main(String[] args) throws Exception {
		if (args.length > 0) {
			BLOCK_PATH = args[0];
		}

		go();
	}

	protected static void go() throws Exception {
		if (BLOCK_PATH.contains("tes")) {
			NOS = 6005940;
		} else {
			NOS = 4003960;
		}
		RES = new byte[NOS];

		OUT = BLOCK_PATH.replaceAll("\\d", "");
		OUT = OUT.replace("//", "/");
		String[] temp = OUT.split("/");
		NAME = temp[temp.length - 2];

		System.out.println(TIME);
		int check = readFiles();
		assertSize(check);
		writeFile();
	}

	private static int readFiles() throws Exception {
		File[] listOfFiles = new File(BLOCK_PATH).listFiles();
		Arrays.sort(listOfFiles);

		int totalLength = 0;
		int pointer = 0;
		for (File file : listOfFiles) {
			if (file.isFile()) {
				int fileLength = (int) file.length();
				totalLength += fileLength;
				byte[] temp = new byte[fileLength];
				FileInputStream fis = new FileInputStream(file);
				fis.read(temp);
				System.arraycopy(temp, 0, RES, pointer, fileLength);
				pointer += fileLength;
				fis.close();
			}
		}
		return totalLength;
	}

	private static void assertSize(int check) {
		if (check != NOS) {
			System.out.println("Incorrect number of bytes read.");
			System.out.println("Read: " + check + " Should have read: " + NOS);
		} else {
			System.out.println("Correct: " + NOS);
		}
	}

	private static void writeFile() throws Exception {
		System.out.println(OUT + NAME + "." + TIME + ".bin");
		File out = new File(OUT + NAME + "." + TIME + ".bin");
		FileOutputStream fos = new FileOutputStream(out);
		fos.write(RES);
	}

	public static String getCurrentTimeStamp() {
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
		Date now = new Date();
		String strDate = sdfDate.format(now);
		return strDate;
	}

}
